#coding=utf-8

import sys
import HTMLParser
import urlparse
import urllib
import urllib2
import cookielib

#https://passport.baidu.com/center?_t=1462678099
url = "https://passport.baidu.com/center?_t=1462678099"
opener = urllib2.build_opener()
result = opener.open(url)
print(result.read())

url = "http://127.0.0.1/testFile/require/cookie.php"
data = {
    'login[password]' : 'anscssss',
    'login[rememberme]' : 1,
    'login[username]' : 'aaa',
    'send' : '',
}
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0',
           'Referer' : 'http://v2245.ants-city.com/Account/Login?ReturnUrl=%2f'}

filename = 'cookie.txt'
#print type(open(filename).read())
#声明一个MozillaCookieJar对象实例来保存cookie，之后写入文件
cookie = cookielib.MozillaCookieJar(filename)
try:
    cookie.load(filename)
except Exception as e:
    pass
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
postdata = urllib.urlencode(data)
#登录教务系统的URL
loginUrl = url
#模拟登录，并把cookie保存到变量
result = opener.open(loginUrl,postdata)
print result.read()

print('=============================')
print('=============================')

#保存cookie到cookie.txt中
cookie.save(ignore_discard=True, ignore_expires=True)
print open(filename).read()
print('=============================')
#利用cookie请求访问另一个网址，此网址是成绩查询网址
gradeUrl = 'http://127.0.0.1/testFile/require/cookie.php'
#请求访问成绩查询网址
result = opener.open(gradeUrl)
print result.read()

